<template>
  <div class="app-container">
    <el-form :model="form" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-row>
        <el-col :span="4">
          <el-form-item prop="boxId">
            <!-- <el-input v-model="form.boxId" style="width: 240px" @input="boxIdChange" placeholder="箱号" /> -->
            <el-input v-model="form.boxId" style="width: 200px" placeholder="外箱号" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="InboxId">
            <el-input v-model="form.InboxId" style="width: 200px" placeholder="内箱号" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-select
            v-model="form.materialNo"
            filterable
            allow-create
            default-first-option
            reserve-keyword
            :loading="materialNoLoading"
            @focus="loadAllMaterialNos"
            placeholder="请选择或输入料号"
            style="width: 100%">
            <el-option
              v-for="item in materialNoOptions"
              :key="typeof item === 'object' ? item.materialNo : item"
              :label="typeof item === 'object' ? item.materialNo : item"
              :value="typeof item === 'object' ? item.materialNo : item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="7" style="margin-left: 5px">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime1"
            @change="onDateChange"
            unlink-panels="false"
            style="width: 100%" />
        </el-col>
        <!-- <el-col :span="1"></el-col>
        <el-col :span="4">
          <div class="mb-4">
            <el-button v-loading="queryLoading" type="primary" :icon="Search" @click="submitForm">查询</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </el-col> -->
        <el-col :span="3" style="margin-left: 5px">
          <el-radio-group
            v-model="radioEl"
            style="border: 1px solid #cdd0d6; width: 100%; text-align: center; padding-left: 2px; padding-right: 2px">
            <el-radio value="detail">详细</el-radio>
            <el-radio value="totalNum">总数</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-loading="exportLoading" type="warning" plain icon="download" @click="exportToExcel2()">导出</el-button>
        <el-button v-loading="queryLoading" type="primary" :icon="Search" @click="submitForm">查询</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-col>
      <el-col :span="4" style="align-items: center">
        <div class="input-with-label">
          <label class="input-label">SN总数: 良品</label>
          <el-input v-model="snQuantityA" style="width: 120px" disabled class="prominent-display" />
        </div>
      </el-col>
      <el-col :span="4" style="align-items: center">
        <div class="input-with-label">
          <label class="input-label">退料</label>
          <el-input v-model="snQuantityS" style="width: 120px" disabled class="prominent-display" />
        </div>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="submitForm" :columns="columns" />
    </el-row>
    <el-row style="margin-top: 8px">
      <el-table :data="storeDataList" border height="65vh">
        <el-table-column prop="boxId" label="外箱号" align="center" v-if="columns.showColumn('boxId')" />
        <el-table-column prop="inBoxId" label="内箱号" align="center" v-if="columns.showColumn('inBoxId')" />
        <el-table-column prop="productId" label="屏体SN" align="center" v-if="columns.showColumn('productId')" />
        <el-table-column prop="materialNo" label="料号" width="200px" align="center" v-if="columns.showColumn('materialNo')" />
        <el-table-column prop="productGrade" label="等级" align="center" v-if="columns.showColumn('productGrade')" />
        <el-table-column prop="model" label="机种" align="center" v-if="columns.showColumn('model')" />
        <el-table-column prop="batchNo" label="批次号" align="center" v-if="columns.showColumn('batchNo')" />
        <el-table-column prop="workOrder" label="华尔升工单" align="center" v-if="columns.showColumn('workOrder')" />
        <el-table-column property="passbackFlag" label="上传状态" align="center" width="90px">
          <template v-slot="scop">
            <!-- <span>{{ scop.row.state }}</span> -->
            <el-tag v-if="scop.row.passbackFlag == 0" type="success">已上传{{ scop.row.passbackFlag }}</el-tag>
            <el-tag v-if="scop.row.passbackFlag == 1" type="warning">重复上传{{ scop.row.passbackFlag }}</el-tag>
            <el-tag v-if="scop.row.passbackFlag > 1 || scop.row.passbackFlag < 0" type="danger">上传失败{{ scop.row.passbackFlag }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storage" label="库房储位" align="center" v-if="columns.showColumn('storage')" />
        <el-table-column prop="orderNo" label="订单号" align="center" v-if="columns.showColumn('orderNo')" />
        <el-table-column prop="relationNo" label="相联单号" align="center" v-if="columns.showColumn('relationNo')" />
        <el-table-column prop="saleNo" label="销售订单号" align="center" v-if="columns.showColumn('saleNo')" />
        <el-table-column prop="createTime" label="入库时间" align="center" v-if="columns.showColumn('createTime')" />
        <el-table-column prop="num" label="数量" align="center" v-if="columns.showColumn('num')" />
      </el-table>
    </el-row>
    <el-row class="pagination-container">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page"
        :page-sizes="[200, 500, 1000]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" />
    </el-row>

    <el-drawer v-model="drawer" title="提示" :with-header="true">
      <span>{{ drawerMessage }}</span>
    </el-drawer>
  </div>
</template>

  
<script setup name="storeinSerch">
import { selectlist, selectMaterialNoAll, selectCount } from '@/api/infoSerch/storeinSerch'
import * as XLSX from 'xlsx'
import _ from 'lodash'

// 获取料号选项列表 - 专门用于过滤选项
function fetchMaterialNoOptions(query) {
  // 确保使用正确的字段名
  const materialNoField = 'materialNo'

  if (query) {
    // 从已加载的选项中过滤
    const filtered = allMaterialNoOptions.value.filter((item) => {
      const materialNo = typeof item === 'object' ? item[materialNoField] : item
      return materialNo.toLowerCase().includes(query.toLowerCase())
    })
    materialNoOptions.value = filtered
  } else {
    // 如果没有查询词，显示所有选项
    materialNoOptions.value = allMaterialNoOptions.value
  }
}

// 加载所有料号选项
function loadAllMaterialNos() {
  console.log('loadAllMaterialNos called')
  if (allMaterialNoOptions.value.length === 0) {
    materialNoLoading.value = true
    selectMaterialNoAll()
      .then((res) => {
        console.log('MaterialNo data format:', res.data) // 调试信息，查看数据格式
        materialNoOptions.value = res.data
        allMaterialNoOptions.value = res.data
        materialNoLoading.value = false
      })
      .catch(() => {
        materialNoLoading.value = false
      })
  } else {
    // 如果已有数据，确保materialNoOptions有值
    if (materialNoOptions.value.length === 0) {
      materialNoOptions.value = allMaterialNoOptions.value
    }
  }
}

const showSearch = ref(true) // 是否显示搜索
const dateRange = ref([])
// 设置默认时间范围：前一天晚上8点到当天早上8点
const defaultTime1 = [new Date(2000, 1, 1, 20, 0, 0), new Date(2000, 1, 2, 8, 0, 0)]
const { proxy } = getCurrentInstance()
const drawer = ref(false)
const drawerMessage = ref('')
const queryLoading = ref(false)
const queryRef = ref()

const total = ref(0)
const pageSize = ref(200)
const page = ref(1)

// 料号选项列表
const materialNoOptions = ref([])
const allMaterialNoOptions = ref([])
const materialNoLoading = ref(false)

//选择查询详细信息或者具体数据
const radioEl = ref('totalNum')
//sn总数
const snQuantityA = ref(0)
const snQuantityS = ref(0)
// 列显隐配置
const columns = ref([
  { visible: true, prop: 'boxId', label: '外箱号' },
  { visible: false, prop: 'inBoxId', label: '内箱号' },
  { visible: false, prop: 'productId', label: '屏体SN' },
  { visible: true, prop: 'materialNo', label: '料号' },
  { visible: true, prop: 'productGrade', label: '等级' },
  { visible: false, prop: 'model', label: '机种' },
  { visible: false, prop: 'batchNo', label: '批次号' },
  { visible: false, prop: 'workOrder', label: '华尔升工单' },
  { visible: false, prop: 'warehourse', label: '客户库房' },
  { visible: false, prop: 'storage', label: '库房储位' },
  { visible: false, prop: 'orderNo', label: '订单号' },
  { visible: false, prop: 'relationNo', label: '相联单号' },
  { visible: false, prop: 'saleNo', label: '销售订单号' },
  { visible: true, prop: 'createTime', label: '入库时间' },
  { visible: true, prop: 'num', label: '数量' }
])

const state = reactive({
  form: {
    boxId: '',
    InboxId: '',
    materialNo: '',
    startTime: '',
    endTime: ''
  },
  storeDataList: [], //存当前页数据
  storeDataListAll: [], //所有页数据
  retInfo: {},
  retMessage: '',
  exportLoading: false
})

const { form, storeDataList, storeDataListAll, retMessage, exportLoading } = toRefs(state)

// 初始化默认时间范围
onMounted(() => {
  // 设置默认时间范围：前一天晚上8点到当天早上8点
  const now = new Date()
  const yesterdayEightPM = new Date(now)
  yesterdayEightPM.setDate(now.getDate() - 1)
  yesterdayEightPM.setHours(20, 0, 0, 0)

  const todayEightAM = new Date(now)
  todayEightAM.setHours(8, 0, 0, 0)

  dateRange.value = [yesterdayEightPM, todayEightAM]
  onDateChange(dateRange.value)
  // 初始化料号选项
  initMaterialNoOptions()
})

// 初始化料号选项
function initMaterialNoOptions() {
  fetchMaterialNoOptions('')
}
//查询按钮
function submitForm() {
  queryLoading.value = true
  if (radioEl.value == 'detail') {
    onDateChange(dateRange.value)
    selectlist({ ...form.value }).then((res) => {
      storeDataListAll.value = res.data
      //console.log(res.data.data)
      retMessage.value = res.msg
      total.value = res.data.length
      getTableData()
      queryLoading.value = false
    })
  } else if (radioEl.value == 'totalNum') {
    selectCount({ ...form.value }).then((res) => {
      snQuantityA.value = res.data.totalNumA
      snQuantityS.value = res.data.totalNumS
      storeDataListAll.value = res.data.list
      //console.log(res.data.data)
      retMessage.value = res.msg
      total.value = res.data.list.length
      getTableData()
      queryLoading.value = false
    })
  }
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm('queryRef')
  // 重置为默认时间范围：前一天晚上8点到当天早上8点
  const now = new Date()
  const yesterdayEightPM = new Date(now)
  yesterdayEightPM.setDate(now.getDate() - 1)
  yesterdayEightPM.setHours(20, 0, 0, 0)

  const todayEightAM = new Date(now)
  todayEightAM.setHours(8, 0, 0, 0)

  dateRange.value = [yesterdayEightPM, todayEightAM]
  onDateChange(dateRange.value)
  form.value.materialNo = ''
  submitForm()
}

//开始时间和结束时间在数组里
const onDateChange = (value) => {
  if (value && value.length === 2) {
    form.value.startTime = new Date(value[0].getTime() + 28800000)
    form.value.endTime = new Date(value[1].getTime() + 28800000)
  } else {
    form.value.startTime = null
    form.value.endTime = null
  }
}

function sizeChange(val) {
  pageSize.value = val
  page.value = 1
  getTableData()
}
function getTableData() {
  storeDataList.value = storeDataListAll.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value)
}
function currentChange(val) {
  page.value = val
  getTableData()
}

// 快速导出所有数据到excel表格，仅前端一个方法
function exportToExcel2() {
  const data = storeDataListAll.value
  //const fileNamePrefix = form.value.boxId
  exportLoading.value = true
  if (data.length === 0) {
    drawer.value = true // 数据为空，显示抽屉并设置消息
    drawerMessage.value = '嗨，没有数据可以导出'
    exportLoading.value = false
  } else {
    exportLoading.value = false
  }
  const now = new Date()
  const fileNameSuffix = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now
    .getDate()
    .toString()
    .padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}-${now
    .getSeconds()
    .toString()
    .padStart(2, '0')}`
  // const fileName = `${fileNamePrefix}_${fileNameSuffix}.xlsx`
  const fileName = `${fileNameSuffix}.xlsx`
  const headers = Object.keys(data[0]).map((key) => ({
    header: key, // 将字段名作为标题
    key: key // key与字段名相同
  }))
  headers.forEach((headerObj) => {
    const customHeaders = {
      boxId: '外箱号',
      inBoxId: '内箱号',
      productId: '批次号',
      materialNo: '屏体SN',
      productGrade: '制程码',
      model: '机种',
      batchNo: '批次号',
      workOrder: '华尔升工单',
      warehourse: '客户库房',
      storage: '库房储位',
      orderNo: '订单号',
      relationNo: '相联单号',
      saleNo: '销售订单号',
      createTime: '入库时间',
      num: '数量'
    }
    if (customHeaders[headerObj.key]) {
      headerObj.header = customHeaders[headerObj.key]
    }
  })
  const sheetData = [headers.map((h) => h.header)] // 第一行是标题
  sheetData.push(...data.map((item) => headers.map((h) => item[h.key])))
  const worksheet = XLSX.utils.aoa_to_sheet(sheetData)

  //const worksheet = XLSX.utils.json_to_sheet(data)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  a.click()
  URL.revokeObjectURL(url)
  exportLoading.value = false
}
// 根据raido 值设置列的可见性
watch(
  () => radioEl.value,
  (newValue) => {
    //清空表格
    storeDataListAll.value = null
    retMessage.value = null
    total.value = 0
    storeDataList.value = null
    //清空总数
    snQuantityA.value = 0
    snQuantityS.value = 0

    // 根据 radioEl 的值设置不同列的可见性
    if (newValue === 'detail') {
      // 详细模式：显示大部分列
      // 只有 materialNo 和 model(作为数量) 显示
      columns.value.forEach((column) => {
        // 只有 materialNo 和 model(作为数量) 显示
        column.visible = [
          'boxId',
          'inBoxId',
          'productId',
          'materialNo',
          'productGrade',
          'model',
          'batchNo',
          'workOrder',
          'warehourse',
          'storage',
          'orderNo',
          'relationNo',
          'saleNo',
          'createTime'
        ].includes(column.prop)
      })
    } else if (newValue === 'totalNum') {
      // 总数模式：只显示特定几列
      columns.value.forEach((column) => {
        // 只有 materialNo 和 model(作为数量) 显示
        column.visible = ['boxId', 'materialNo', 'productGrade', 'createTime', 'num'].includes(column.prop)
      })
    }
  }
)
</script>
<style scoped>
.pagination-container {
  display: flex;
  justify-content: right;
}
.input-with-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
}

.prominent-display :deep(.el-input__inner) {
  font-size: 16px;
  font-weight: bold;
  color: #1a1a1a;
  text-align: center;
  background-color: #f0f9eb; /* 浅绿色背景，更醒目 */
}
.prominent-display :deep(.el-input__wrapper) {
  background-color: #f0f9eb;
}
</style>